package com.neuedu.shop.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.neuedu.shop.common.Result;
import com.neuedu.shop.entity.User;
import com.neuedu.shop.entity.request.PageParam;
import com.neuedu.shop.entity.request.RequestUser;
import com.neuedu.shop.entity.request.UserLogin;
import com.neuedu.shop.entity.vo.UserVO;
import com.neuedu.shop.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 前后端分离：
 * JSON
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
public class IndexController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result login(@RequestBody UserLogin user) {
        if (userService.login(user)) {
            return Result.success("登录成功");
        }
        return Result.fail("失败");
    }

    @PostMapping
    public Result add(@RequestBody User user) {
        if (userService.register(user)) {
            return Result.success("添加成功");
        }
        return Result.fail("添加失败");
    }

    @DeleteMapping("/{id}")
    public String delete(@PathVariable("id") Long id) {
        if(userService.removeById(id)){
            return "删除成功";
        }
        return "删除失败";
    }

    @PutMapping
    public String update(@RequestBody User user) {
        UpdateWrapper<User> userUpdateWrapper=new UpdateWrapper<>();
        userUpdateWrapper.set("username",user.getUsername());
        userUpdateWrapper.eq("id",user.getId());
        if(userService.update(userUpdateWrapper)){
            return "修改成功";
        }
        return "修改失败";
    }

    @GetMapping("/{id}")
    public User getUser(@PathVariable("id") Long id) {
        return userService.getById(id);
    }

    @PostMapping("/users")
    public Result<IPage<UserVO>> users(@RequestBody RequestUser requestUser) {
        return Result.success(userService.getUsers(requestUser));
    }
}
